<template>
  <div class="main">
    <div>
      <ElCard>
        <template #header>用户注册</template>

        <div>
          <ElForm :model="reginfo" ref="myform" :rules="rules">
            <ElFormItem prop="username">
              <ElInput v-model="reginfo.username" placeholder="登录名"></ElInput>
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput :show-password="true" v-model="reginfo.password" placeholder="密码"></ElInput>
            </ElFormItem>
            <ElFormItem>
              <ElButton @click="regss" type="primary">注册</ElButton>
              <ElButton @click="logthss" type="primary">返回登陆</ElButton>
            </ElFormItem>
          </ElForm>
        </div>
      </ElCard>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessageBox, FormRules, ElButton, ElCard, ElForm, ElFormItem, ElInput, FormInstance } from 'element-plus'
import { L12030 } from '../../api/L12030'
import { BaseResult } from '../../ts/BaseResult'
import { TbUser } from '../../ts/UserInfo'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const reginfo = ref(new TbUser())
const checkUsername = (rule: any, value: string, cb: any) => {
  console.log(rule)
  if (/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/.test(value)) {
    cb()
  } else {
    cb(new Error('用户名必须是字母开头，且长度是4-15位'))
  }
}
// 校验规则定义
const rules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: '登录名称必须填写',
    },
    {
      validator: checkUsername,
    },
  ],
  password: [
    {
      required: true,
      message: '密码必须填写',
    },
  ],
})

function logthss(){
  router.push('/')
}

function regss() {
  L12030.post('/user', reginfo.value, (data: BaseResult) => {
    if (data.success) {
      ElMessageBox.alert(data.message).then(() => {
        router.push('/')
      })
    }
    ElMessageBox.alert(data.message)
  })
}
</script>
<style lang="scss" scoped>
.main {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0.7; 
  > div {
    transform: translateY(-10vh);
    min-width: 20vw;
  }
}
</style>
